import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Conversation } from './conversation.entity';
import { ConversationParticipant } from './conversation-participant.entity';
import { Message } from './message.entity';

@Injectable()
export class ChatService {
  constructor(
    @InjectRepository(Conversation)
    private conversationRepository: Repository<Conversation>,
    @InjectRepository(ConversationParticipant)
    private conversationParticipantRepository: Repository<ConversationParticipant>,
    @InjectRepository(Message)
    private messageRepository: Repository<Message>,
  ) {}

  async createConversation(participantIds: number[]): Promise<Conversation> {
    // 创建对话
    const conversation = this.conversationRepository.create();
    const savedConversation =
      await this.conversationRepository.save(conversation);

    // 添加参与者
    for (const participantId of participantIds) {
      const participant = this.conversationParticipantRepository.create({
        visitorUserId: participantId,
        visitedUserId: savedConversation.id,
      });
      await this.conversationParticipantRepository.save(participant);
    }

    return savedConversation;
  }

  async addUserToConversation(
    conversationId: number,
    userId: number,
  ): Promise<ConversationParticipant> {
    const participant = this.conversationParticipantRepository.create({
      visitorUserId: userId,
      visitedUserId: conversationId,
    });
    return await this.conversationParticipantRepository.save(participant);
  }

  async getConversationsByUserId(userId: number): Promise<Conversation[]> {
    const participants = await this.conversationParticipantRepository.find({
      where: { visitorUserId: userId },
      relations: ['conversation'],
    });

    return participants.map((p) => p.conversation);
  }
}
